#include "Crop.h"
#include <opencv\highgui.h>

Crop::Crop(void) : Filter(2, 1), expliciteSize(false)
{
}

Crop::Crop(const cv::Size &size) : Filter(2, 1), expliciteSize(true), size(size)
{
	outputs[0] = cv::Mat(size.height, size.width, CV_8UC3);
}

Crop::~Crop(void)
{
}

void Crop::Process()
{
	int *p = inputs[1]->ptr<int>(0);
	cv::Rect cropRect = cv::Rect(p[0], p[1], p[2], p[3]);

	if (p[0] + p[1] + p[2] + p[3] == 0)
	{
		outputs[0] = cv::Mat(0, 0, CV_32SC1);
		outputValid[0] = false;
		return;
	}

	if (expliciteSize)
	{
		cv::Rect newRect(
			cropRect.x + (cropRect.width - size.width)/2,
			cropRect.y + (cropRect.height - size.height)/2,
			size.width,
			size.height);

		newRect.x = MAX(0, newRect.x);
		newRect.y = MAX(0, newRect.y);

		if (newRect.x + newRect.width >= inputs[0]->cols)
			newRect.x = inputs[0]->cols - newRect.width - 1;
		if (newRect.y + newRect.height >= inputs[0]->rows)
			newRect.y = inputs[0]->rows - newRect.height - 1;

		outputs[0] = (*inputs[0])(newRect);
	}
	else
	{
		outputs[0] = (*inputs[0])(cropRect);
	}
}
